# -*- coding: utf-8 -*-
# Version:python3.7
# -------------------------------------------------------------------------------
# Author:       zhuxinjun
# Date:         2020-05-31 23:19
# Description:  604500467@qq.com
# -------------------------------------------------------------------------------
import base64,io,xlwt
from odoo import api, fields, models, _
class WizardExportData(models.TransientModel):
    _name = "wizard.export.data"
    _description = "导出数据"
    start_date = fields.Date(string="开始时间")
    end_date = fields.Date(string="结束时间")
    already_export = fields.Boolean(string='已导出')
    file_name = fields.Char(string='文件名称', store=True)
    xls_file = fields.Binary(string='点击下载数据', attachment=True)

    # 返回data
    def _get_content(self,model_name,fields_infos):
        content_list = []
        records = self.sudo().env[model_name].search([
            ("create_date", "<=", self.end_date),
            ("create_date", ">=", self.start_date)
        ])

        for record in records:
            result_list = []
            for fields_info in fields_infos:
                # 'selection'
                field_value = ''
                if fields_info[2] in ['one2many','many2one','many2many']:
                    field_value = record[fields_info[0]].name if hasattr(record[fields_info[0]],'name') else 0
                elif fields_info[2] =='date':
                    field_value = record[fields_info[0]].strftime('%Y-%m-%d')
                    result_list.append(record[fields_info[0]].strftime('%Y-%m-%d'))
                elif fields_info[2] =='datetime':
                    field_value = record[fields_info[0]].strftime('%Y-%m-%d %H:%M:%S')
                elif fields_info[2]=='selection':
                    field_value = dict(fields_info[3]).get(record[fields_info[0]])
                else:
                    field_value =record[fields_info[0]]
                field_value ='' if field_value ==False else field_value
                result_list.append(field_value)
            content_list.append(result_list)
        return content_list

    def export_data_file(self):
        model_name = self._context.get("modelName")
        view_id = self._context.get("viewId")
        view_type = self._context.get("viewType")
        not_fileds=['id','display_name','website_message_ids'] #'create_uid',
        fields_infos = [(key, value['string'],value['type'],value.get('selection')) for key, value in self.env[model_name].fields_get().items()
                       if value['store']==True and  not key.startswith('image') and not key.startswith('message_') and not key.startswith('activity') and key not in not_fileds and value['type']!='binary']
        excel_header = [el[1] for el in fields_infos]
        result =[excel_header] + self._get_content(model_name,fields_infos)

        wbk = xlwt.Workbook()
        sheet = wbk.add_sheet('Sheet1', cell_overwrite_ok=True)
        style = xlwt.XFStyle()
        # 居中
        al = xlwt.Alignment()
        al.horz = 0x02
        al.vert = 0x01
        style.alignment = al
        # 外边框
        borders = xlwt.Borders()
        borders.left = 1
        borders.right = 1
        borders.top = 1
        borders.bottom = 1
        borders.bottom_colour = 0x3A
        style.borders = borders
        # 字体
        font = xlwt.Font()
        font.name = u'微软雅黑'
        font.height = 220
        style.font = font

        for i in range(len(result)):
            for j in range(len(result[i])):
                sheet.write(i, j, result[i][j], style)

        fp = io.BytesIO()
        wbk.save(fp)
        fp.seek(0)
        data = fp.read()
        fp.close()

        file_name = "%s_%s_%s数据.xls" % (self.env[model_name]._description,str(self.start_date), str(self.end_date))
        self.write({'already_export': True, 'xls_file': base64.b64encode(data), 'file_name': file_name})
        return {
            'type': 'ir.actions.act_window',
            'view_mode': 'form',
            'res_model': 'wizard.export.data',
            'target': 'new',
            'res_id': self.id,
        }
        # return {"type": "ir.actions.act_window_close"}